package com.apps.ftapp.activity;


import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;


import androidx.core.app.ActivityCompat;

import com.apps.ftapp.R;
import com.apps.ftapp.adapter.MyLessonListAdapter;
import com.apps.ftapp.db.Kj;
import com.apps.ftapp.db.Lesson;
import com.apps.ftapp.db.LessonChild;
import com.apps.ftapp.model.MyLessonListModel;
import com.apps.ftapp.model.Queding;
import com.apps.ftapp.ui.MyProgressDialog;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.SDCardUtils;
import com.apps.ftapp.util.Tools;
import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTask;
import com.duobeiyun.util.DuobeiYunClient;
import com.google.gson.Gson;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.maning.mndialoglibrary.MProgressDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;

public class MyLessonListActivity extends BaseActivity implements MyLessonListAdapter.MyClickListener {

    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private MyProgressDialog dialog;
//    @BindView(R.id.progress_lin)
//    LinearLayout progress_lin;

    private String id;
    private String title;
    private String type = ""; //normal 是点播棵  live 直播课

    private float currentProgress = 0.0f;

    private String filePath;


    private final Gson gson = new Gson();

//    private Random random = new Random();

    private String dirName = SDCardUtils.getSDCardPath() + "duobeiyun/";

    private String roomId;


    private Context mContext;

    private List<MyLessonListModel.DataBean> dataList = new ArrayList();
    private MyLessonListAdapter myLessonListAdapter;


    private int current = 0;


    final static String DOWNLOAD_URL = "";
    private MProgressDialog mMProgressDialog;


    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_lesson_list);
        ButterKnife.bind(this);
        dialog = MyProgressDialog.createDialog(this);
        dialog.setCanceledOnTouchOutside(false);
        setTitle("我的课程");

        Aria.download(this).register();
        mContext = this;


        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        id = bundle.getString("id");
        title = bundle.getString("title");
        type = bundle.getString("type");

        if (type == null || type.equals("")) {
            type = "live";
        }
        L.i("main", ":::" + id);

        quanxian();


        initView();

        loadData();

    }


    private void loadData() {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("courseId", id);
        L.i("main", "token111111111111:" + Constant.token + "::" + Constant.uid + "::" + id);

        Async.post("my/courses/lessons/list", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", ">>>>>" + new String(responseBody));
                    MyLessonListModel result = gson.fromJson(new String(responseBody), MyLessonListModel.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {
                        if (null != result.getData() && result.getData().size() > 0) {
                            for (MyLessonListModel.DataBean d : result.getData()) {
                                List<LessonChild> childList = DataSupport.where("childId = ?", d.getId() + "").find(LessonChild.class);
                                if (null != childList && childList.size() > 0) {
                                    d.setIsDownload("1");
                                }
                            }
                        }
                        dataList.addAll(result.getData());
                        myLessonListAdapter.addRes(result.getData());
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                //L.i("main", ">>>>>" + new String(responseBody));

            }
        });

    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning(DOWNLOAD_URL)
    protected void running(DownloadTask task) {
        int p = task.getPercent();    //任务进度百分比
        String speed = task.getConvertSpeed();    //转换单位后的下载速度，单位转换需要在配置文件中打开
//        String speed1 = task.getSpeed(); //原始byte长度速度


        L.i("main", p + ":::::::::" + speed);
//        int pro = (int) (currentProgress * 100);


        updateprogress(current, p);


//        if (mMProgressDialog != null) {
//            if (p == 100) {
//
//                mMProgressDialog.dismiss();
//            } else {
//                mMProgressDialog.setDialogProgress(currentProgress, "视频下载进度: " + p + "%");
//            }
//        }


//        int pro = (int) (currentProgress * 100);

//        L.i("main",p+":::::::::"+currentProgress+":::::::"+pro);

//        currentProgress += 0.1;
//        mMProgressDialog.setDialogProgress(p, "视频下载进度: " + pro + "%");

    }


    /**
     * 第一种方法 更新对应view的内容
     *
     * @param position 要更新的位置
     */
    private void updateSingle(int position) {
        /**第一个可见的位置**/
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        /**最后一个可见的位置**/
        int lastVisiblePosition = listView.getLastVisiblePosition();

        /**在看见范围内才更新，不可见的滑动后自动会调用getView方法更新**/
        if (position >= firstVisiblePosition && position <= lastVisiblePosition) {
            /**获取指定位置view对象**/
            View view = listView.getChildAt(position - firstVisiblePosition);
            TextView textView = view.findViewById(R.id.huancunkecheng);
            textView.setText("查看视频");
        }
    }

    private void updateKj(int position) {
        /**第一个可见的位置**/
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        /**最后一个可见的位置**/
        int lastVisiblePosition = listView.getLastVisiblePosition();

        /**在看见范围内才更新，不可见的滑动后自动会调用getView方法更新**/
        if (position >= firstVisiblePosition && position <= lastVisiblePosition) {
            /**获取指定位置view对象**/
            View view = listView.getChildAt(position - firstVisiblePosition);
            TextView textView = view.findViewById(R.id.huancunkejian);
            textView.setText("查看课件");
        }
    }

    private void updateprogress(int position, int progress) {
        /**第一个可见的位置**/
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        /**最后一个可见的位置**/
        int lastVisiblePosition = listView.getLastVisiblePosition();

        /**在看见范围内才更新，不可见的滑动后自动会调用getView方法更新**/
        if (position >= firstVisiblePosition && position <= lastVisiblePosition) {
            /**获取指定位置view对象**/
            View view = listView.getChildAt(position - firstVisiblePosition);
            TextView textView = view.findViewById(R.id.huancunkecheng);
            textView.setText(progress + "%");
        }
    }

    @Download.onTaskComplete(DOWNLOAD_URL)
    void taskComplete(DownloadTask task) {
        //在这里处理任务完成的状态
        L.i("main", task.getConvertFileSize() + ":::::在这里处" + dirName + "理任务完成的状态::::" + task.getDownloadPath());
        L.i("main", ":::" + dirName);
        //解压
        try {
            // ZipUtil.unZip(task.getDownloadPath(),dirName);
        } catch (Exception e) {

        }

//        promptDialog.dismiss();

        if (null != mMProgressDialog) {
            mMProgressDialog.dismiss();
        }


        MyLessonListModel.DataBean bean = dataList.get(current);


        //先查询是否添加过此课程
        List<Lesson> lessonList = DataSupport.where("lessonid = ?", id + "").find(Lesson.class);
        if (null != lessonList && lessonList.size() > 0) {
            //更新
//                    L.i("main","................."+lesson2.getLessonid());
            ContentValues values = new ContentValues();
            values.put("num", lessonList.get(0).getNum() + 1);
            //更新大小

            DataSupport.updateAll(Lesson.class, values, "lessonid = ?", id + "");


            //判断是否已经下过
            List<LessonChild> childList = DataSupport.where("childId = ?", bean.getId() + "").find(LessonChild.class);
            if (null != childList && childList.size() > 0) {
            } else {
                StringBuffer sb = new StringBuffer();
                if (null != bean.getTeachers() && bean.getTeachers().size() > 0) {
                    for (MyLessonListModel.DataBean.TeachersBean b : bean.getTeachers()) {
                        sb.append(b.getNickname() + " ");
                    }
                }

                LessonChild lessonChild1 = new LessonChild();
                lessonChild1.setSizes(task.getConvertFileSize());
                lessonChild1.setTitle(bean.getTitle());
                lessonChild1.setTeacher(sb.toString());
                lessonChild1.setType(bean.getTbutton());
                lessonChild1.setLessonId(id);
                lessonChild1.setChildId(bean.getId());
                lessonChild1.setRoomId(bean.getRoomId());
                lessonChild1.setFilePath(dirName);
                lessonChild1.setTimes("上课时间：" + bean.getStartTime() + "至" + bean.getEndTime());
                lessonChild1.save();

            }
        } else {
            //新增
            Lesson lesson = new Lesson();
            lesson.setNum(1);
            lesson.setTitle(title);
            lesson.setSizes(task.getConvertFileSize());
            lesson.setLessonid(id);
            lesson.save();//将数据写入到数据库中

            StringBuffer sb = new StringBuffer();
            if (null != bean.getTeachers() && bean.getTeachers().size() > 0) {
                for (MyLessonListModel.DataBean.TeachersBean b : bean.getTeachers()) {
                    sb.append(b.getNickname() + " ");
                }
            }

            LessonChild lessonChild1 = new LessonChild();
            lessonChild1.setSizes(task.getConvertFileSize());
            lessonChild1.setTitle(bean.getTitle());
            lessonChild1.setTeacher(sb.toString());
            lessonChild1.setType(bean.getTbutton());
            lessonChild1.setLessonId(id);
            lessonChild1.setChildId(bean.getId());
            lessonChild1.setFilePath(dirName);
            lessonChild1.setRoomId(bean.getRoomId());
            lessonChild1.setTimes("上课时间：" + bean.getStartTime() + "至" + bean.getEndTime());
            lessonChild1.save();
        }
        updateSingle(current);
        Toasty.normal(getApplicationContext(), "缓存完成!").show();


    }


    @Download.onTaskFail
    void taskFail(DownloadTask task) {
        if (mMProgressDialog != null) {
            mMProgressDialog.dismiss();
        }
        Toasty.normal(getApplicationContext(), "缓存失败!").show();
    }

    private void initView() {

        SQLiteDatabase db = Connector.getDatabase();

        List<Lesson> allSongs = DataSupport.findAll(Lesson.class);
        for (Lesson l : allSongs) {
            L.i("main", "............" + l.getTitle());
        }


        myLessonListAdapter = new MyLessonListAdapter(getApplicationContext(), dataList, id, this, type);
        listView.setAdapter(myLessonListAdapter);


    }

    private void updatelesson(final MyLessonListModel.DataBean temp) {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("lid", temp.getId());
        Async.post("my/courseskan", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    Queding result = gson.fromJson(new String(responseBody), Queding.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {
                        Intent intent = null;
                        if (temp.getAndtype().equals("live") || temp.getTbutton().equals("直播中")) {
                            intent = new Intent(getApplicationContext(), CustomizedLiveActivity.class);
                        } else {
                            intent = new Intent(getApplicationContext(), CusomizedPlayBackActivity.class);
                        }

                        if (type.equals("normal")) {
                            intent = new Intent(getApplicationContext(), DefPlaybackActivity.class);
                        }

//                Intent intent = new Intent(getApplicationContext(), ZhiBoActivity.class);
//                Intent intent = new Intent(getApplicationContext(), CusomizedPlayBackActivity.class);
//                Intent intent = new Intent(getApplicationContext(),DbHuifangActivity.class);
//
//                Intent intent = new Intent(getApplicationContext(),DefPlaybackActivity.class);
//                Intent intent = new Intent(getApplicationContext(),PlayerActivity.class);
                        intent.putExtra("appKey", Constant.APPKEY);
//                com.duobeiyun.def.controller.DefPlaybackActivity
                        intent.putExtra("nickname", Constant.nickname);
                        intent.putExtra("partner", Constant.PID);
                        intent.putExtra("roomId", temp.getRoomId());
                        intent.putExtra("uid", Constant.uid);
                        intent.putExtra("title", temp.getTitle());
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                        getApplicationContext().startActivity(intent);
                    } else {

                        return;
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                L.i("main", ">>>>>" + new String(responseBody));

            }
        });
    }

    private void updatelesson2(final LessonChild temp) {

        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("lid", temp.getChildId());
        Async.post("my/courseskan", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    Queding result = gson.fromJson(new String(responseBody), Queding.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {
                        HashMap map = new HashMap();
                        map.put("id", Tools.isNull(temp.getChildId()));
                        map.put("filePath", Tools.isNull(temp.getFilePath()));
                        map.put("roomId", Tools.isNull(temp.getRoomId()));
                        map.put("title", Tools.isNull(temp.getTitle()));
                        L.i("main", "::::" + map.toString());
                        ActivitySkipUtil.skipAnotherActivity(MyLessonListActivity.this, CustomizedOffinePlayBackActivity.class, map);
                    } else {
                        return;
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                L.i("main", ">>>>>" + new String(responseBody));

            }
        });

    }

    @Override
    public void clickListener(View v) {
        switch (v.getId()) {
            case R.id.top_container:

                int position = (int) v.getTag();
                MyLessonListModel.DataBean dataBean = dataList.get(position);
                updatelesson(dataBean);
                break;


            case R.id.huancunkejian:
                current = (int) v.getTag();
                MyLessonListModel.DataBean bean1 = dataList.get(current);
                roomId = bean1.getRoomId();
                // Check if we have write permission
//                quanxian();
                List<Kj> kjList = DataSupport.where("lessonid = ?", bean1.getId() + "").find(Kj.class);
                if (null != kjList && kjList.size() > 0) {
                    String uri = dirName + bean1.getId() + ".pdf";
                    Intent intent = new Intent();
                    intent.setClass(MyLessonListActivity.this, PdfActivity.class);
                    intent.putExtra("uri", uri);
                    startActivity(intent);
                    //Intent intent = OpenFiles.getPdfFileIntent(dirName + bean1.getId() + ".pdf");
                    //startActivity(intent);
                } else {
                    File file1 = new File(dirName);
                    //不存在创建
                    if (!file1.exists()) {
                        file1.mkdir();
                    }

                    L.i("main", "::::" + bean1.getKjdownurl());

                    dialog.setMsg("下载中");
                    dialog.show();
                    download(bean1.getKjdownurl(), file1.getAbsolutePath() + "/" + bean1.getId() + ".pdf", current);
                }
                break;

            case R.id.huancunkecheng:
                //
//                DuobeiYunClient.
                File file = new File(dirName);
                //不存在创建
                if (!file.exists()) {
                    file.mkdir();
                }

                //
                current = (int) v.getTag();

                MyLessonListModel.DataBean bean = dataList.get(current);

                List<LessonChild> childList = DataSupport.where("childId = ?", bean.getId() + "").find(LessonChild.class);
                if (null != childList && childList.size() > 0) {
                    updatelesson2(childList.get(0));

                } else {
//                    promptDialog = new PromptDialog(this);
//                    promptDialog.showLoading("缓存中..");


                    //showProgressDialog05();

                    String DOWNLOAD_URL = DuobeiYunClient.BASE_URL + bean.getRoomId() + ".zip";
                    L.i("main", DOWNLOAD_URL);
                    filePath = dirName + bean.getRoomId() + ".zip";
                    L.i("trueparam", filePath);
                    Aria.download(this)
                            .load(DOWNLOAD_URL)     //读取下载地址
                            .setDownloadPath(filePath) //设置文件保存的完整路径
                            .start();   //启动下载
                }


                break;


        }


    }

    /**
     * 带有下载进度的显示
     */
    private void configDialogWithProgress() {
        //新建一个Dialog
        mMProgressDialog = new MProgressDialog.Builder(mContext)
                .isCanceledOnTouchOutside(true)
//                .setBackgroundWindowColor(getMyColor(R.color.color_answer_chose))
                .setProgressRimColor(getMyColor(R.color.color_answer_chose))
                .setProgressRimWidth(1)
                .setOnDialogDismissListener(new MProgressDialog.OnDialogDismissListener() {
                    @Override
                    public void dismiss() {

                        L.i("main", "OnDialogDismissListener");
//                        Aria.download(this).load(DOWNLOAD_URL).cancel();
//                        mMProgressDialog.dismiss();
//                        mHandler.removeCallbacksAndMessages(null);
                    }
                })
                .build();
    }


    private int getMyColor(int colorID) {
        return getApplicationContext().getResources().getColor(colorID);
    }

    public void showProgressDialog05() {
        configDialogWithProgress();
        mMProgressDialog.showWithProgress();
//        initTimer();
    }


    private void quanxian() {
        int permission = ActivityCompat.checkSelfPermission(MyLessonListActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    MyLessonListActivity.this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

    @Override
    protected void onResume() {
        //loadData();
        super.onResume();
    }

    private void download(String url, String filePath, final int current) {
        //判断SDcard是否存在并且可读写
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toasty.normal(getApplicationContext(), "没有权限").show();
            dialog.dismiss();
            return;
        }

        if ("".equals(Tools.isNull(url))) {
            dialog.dismiss();
            Toasty.normal(getApplicationContext(), "缓存错误").show();
            return;
        }
        L.i("main", url + "___" + url);
        FileDownloader.getImpl().create(url)
                .setPath(filePath)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        //Toasty.normal(getApplicationContext(), "正在缓存，请稍后").show();
                        //Toast.makeText(MyLessonListActivity.this,"正在缓存，请稍后",Toast.LENGTH_LONG);
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        //此处更新进度
                        int percent = (int) ((double) soFarBytes / (double) totalBytes * 100);
                        L.i("main", "(" + percent + "%" + ")");


                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        dialog.dismiss();
                        L.i("main", "task.getTargetFilePath():::" + task.getTargetFilePath());
                        File f = new File(task.getTargetFilePath());
                        L.i("main", ">>>" + f.length());


                        MyLessonListModel.DataBean bean1 = dataList.get(current);

                        //先查询是否添加过此课程
                        List<Kj> kjList = DataSupport.where("lessonid = ?", bean1.getId() + "").find(Kj.class);
                        if (null != kjList && kjList.size() > 0) {
                            //更新
                            L.i("main", "........gjus........." + bean1.getId());

                            //


                            ContentValues values = new ContentValues();
//                            values.put("num",kjList.get(0).getNum()+1);
                            values.put("sizes", Tools.getPrintSize(f.length()));
                            DataSupport.updateAll(Kj.class, values, " lessonid = ? ", bean1.getId() + "");

                        } else {
//                    Random ran = new Random();
                            //新增
                            Kj lesson = new Kj();
                            lesson.setNum(1);
                            lesson.setTitle(bean1.getTitle());
                            lesson.setSizes(Tools.getPrintSize(f.length()));
                            lesson.setLessonid(bean1.getId());
                            lesson.save();//将数据写入到数据库中
                        }
                        Toasty.normal(getApplicationContext(), "缓存完成!").show();
                        updateKj(current);
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        dialog.dismiss();
                        L.i("main", "::" + task.getErrorCause());
                        Toasty.normal(getApplicationContext(), "缓存失败!").show();
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        dialog.dismiss();
                    }
                }).start();
    }


}
